<?php
class MovealbumsCtl extends BaseCtl {
	public function MovealbumsCtl(){
		parent::BaseCtl();
	}
    public function isPostback(){
    	return 'movealbums' == $this->getPost('pagename');
    }
    
    public function loadData(){
    	$form = $this->getMovealbumsForm();
    	
    	$form->setSearchUserId($this->getPost('searchUserId'));
    	$form->setMoveUserId($this->getPost('moveUserId'));
    	
    	// and now the selecgted
    	$selected = $this->getNonEmpty($this->getPost('selected'));
    	
    	$sel = array();
    	foreach($selected as $crt){
    		$sel[$crt] = 'sel';
    	}
    	
    	$form->setSelected($sel);
    }
    
    public function update(){
		try {
			$form = $this->getMovealbumsForm(); 
			$updateUserId = $form->getSearchUserId(); 
			
			// get the albums for the form
			$service = new Service();
			$albums = $service->searchAlbums($updateUserId, "");
			
			$form->setAlbums($albums);
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
    }
    
    public function move(){
		try {
			$form = $this->getMovealbumsForm();
			$selected = $form->getSelected();
			$moveId = $form->getMoveUserId(); 
			
			if(count($selected) == 0){
				// at least one album must be selected
				throw new Exception('Please select at least one album to move');
			}
			else {
				$nr = count($selected);
				
				$albums = $form->getSelectedAlbums();
				$id = $albums[0]->getUserId();
				
				$ids = array();
				foreach($albums as $album){
					$ids[] = $album->getId();
				}
				
				if($id == $moveId){
					throw new Exception('The two users (origin and destination) must be different');
				}
				
				// move the albums
				$service = new Service();
				$service->setAlbumsId($ids, $moveId);
				
				// remove the albums from the form
				$form->removeAlbums($ids);
				
				// add some message for confirmation
				$word = $nr > 1 ? "$nr albums have been" : 'album has been';
				HtmlUtil::addMessage("The $word successfully moved");
			}
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
    }
} 
?>